<template>
  <van-tabs v-model:active="active" sticky color="#000000" title-active-color="#000000" @click-tab="clickTab">
    <van-tab :title="category.title" title-class="tab-title" v-for="category in categories" :key="category.showType">
      <!-- tags筛选 -->
      <div class="filter-tags">
        <template v-for="(hotTag, index) in previewHotTags" :key="hotTag.tagId">
          <van-tag round class="tag" :class="{ active: activeTagIndex === index }" @click="clickTag(hotTag, index)">#{{
            hotTag.tagName }}</van-tag>
        </template>
        <van-tag round class="tag" @click="clickTag()">#更多<van-icon name="arrow-down" /></van-tag>
      </div>
    </van-tab>

    <!-- tab右侧图标 -->
    <template #nav-right><van-icon name="wap-nav" class="more" @click="showCategoryPopup" /></template>

    <!-- 筛选规则: 排序 - 日期 - 地点 -->
    <template #nav-bottom>
      <div class="rules">
        <van-dropdown-menu active-color="#FF1D41">
          <van-dropdown-item v-model="sorting" class="sort" :title-class="sorting != 'weight' ? 'sort-class' : ''"
            :options="sortOptions" @change="changeSorting" />
          <!-- 排序规则 -->

          <van-dropdown-item ref="dateDropDown" title="开演日期" class="show-date"
            :title-class="dateTitleClass"><!-- 日期 选择 -->
            <div class="calendar">
              <van-calendar ref="calendar" :default-date="defaultDate" :poppable="false" :show-mark="false"
                :show-confirm="false" type="range" :show-subtitle="false" :show-title="false" switch-mode="none"
                :allow-same-day="true" :max-date="maxDate" :formatter="formatter" row-height="30"
                class="custom-calendar" @select="onSelect">
                <template #month-title="{ date }">
                  <div class="month-title">
                    {{ `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}` }}
                  </div>
                </template>

                <template #footer>
                  <div class="buttons">
                    <van-button round plain hairline block size="normal" @click="reset">清空</van-button>
                    <van-button round hairline block size="normal" color="#FF1D41" @click="confirm">确定</van-button>
                  </div>
                </template>
              </van-calendar>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="演出城市" class="show-city" :title-class="cityTitleClass" ref="cityDropDown">
            <!-- 城市选择 -->

            <show-city :allCity="allCityFilter" :hotAllCity="hotAllCityFilter" :hotTopCity="hotTopCityFilter"
              :locationCity="locationCityFilter" @update:cityId="updateCityId" @close:cityOption="closeCityOption"
              @cityConfirmed="handleCityConfirmed" />
          </van-dropdown-item>
        </van-dropdown-menu>
      </div>
    </template>
  </van-tabs>
</template>

<script setup>
import ShowCity from './ShowCity.vue'

import { formatDateToYYYYMMDD, formatDateToMMDD } from '@/tool/index.js'
import { ref, reactive, computed, onMounted, useTemplateRef, watch, toRefs, nextTick } from 'vue'
import { fetchCategoryList, fetchShowCity, fetchShowFilterTag, fetchShowList } from '@/api/index.js'

import { useStore } from '@/stores/index.js'
import { showToast } from 'vant'

const store = useStore()

const dateDropDownRef = useTemplateRef('dateDropDown')
const calendarRef = useTemplateRef('calendar')

const cityDropDownRef = useTemplateRef('cityDropDown')

const emit = defineEmits(['update:loading', 'openCategoryPopup', 'close:loading', 'showMoreTags'])

const props = defineProps([
  'clearDate',
  'clearTag',
  'clearCity',
  'showTypeName',
  'routeSorting',
  'routeShowTypeName',
  'routeShowType',
])
const {
  clearDate,
  clearTag,
  clearCity,
  showTypeName,
  routeSorting,
  routeShowTypeName,
  routeShowType,
} = toRefs(props)

//演出分类
const categories = ref([])

// 激活的演出分类索引
const active = ref(store.currentCategoryIndex > 0 ? store.currentCategoryIndex + 1 : 0)

//根据 showType 获取 showTypeName
const getShowTypeName = (showType) => {
  const category = categories.value?.find((category) => category.showType == showType)

  console.log(`当前分类showTypeName:${category ? category.showTypeName : 'All'}`)
  return category ? category.showTypeName : 'All'
}

const showType = computed(() => {
  // 优先级1: 检查路由中的 showTypeName 参数
  if (routeShowTypeName.value) {
    console.log('路由中的 showTypeName参数：', routeShowTypeName.value)
    return routeShowTypeName.value
  }

  // 优先级2: 检查路由中的 showType参数
  if (routeShowType.value) {
    console.log('路由中的 showType参数：', routeShowType.value)
    return getShowTypeName(routeShowType.value)
  }

  // 优先级3: 检查当前激活的分类
  if (categories.value && categories.value[active.value]) {
    return categories.value[active.value].showTypeName
  }

  // 优先级4: fallback 到 props 传入的默认值
  return showTypeName.value || 'All'
})

//  排序规则
const sortOptions = ref([
  { text: '推荐排序', value: 'weight' },
  { text: '折扣优先', value: 'discount' },
])
// 当前选中的筛选规则  routeSorting
const sorting = ref(routeSorting.value || 'weight')

const isDateConfirmed = ref(false)
const isCityConfirmed = ref(false)

const dateTitleClass = computed(() => {
  // 当选择了日期范围并且已确认时，应用 sort-class 样式
  return dateFilter.beginDateTime && dateFilter.endDateTime && isDateConfirmed.value
    ? 'sort-class'
    : ''
})

const cityTitleClass = computed(() => {
  // 当选择了城市并且已确认时，应用 sort-class 样式
  return showCityList.value && isCityConfirmed.value ? 'sort-class' : ''
})

//筛选日期选则
const defaultDate = ref(null)
//最大可查询日期
const maxDate = ref(new Date(new Date().getFullYear(), 11, 31))
//当前选中的开演时间
const dateFilter = reactive({
  beginDateTime: null,
  endDateTime: null,
})

// 添加重置方法来清除确认状态
const resetDateConfirmation = () => {
  isDateConfirmed.value = false
}

const resetCityConfirmation = () => {
  isCityConfirmed.value = false
}

const handleCityConfirmed = () => {
  // 设置城市已确认标志
  isCityConfirmed.value = true
}

watch(clearDate, (newDate) => {
  if (newDate) {
    dateFilter.beginDateTime = null
    dateFilter.endDateTime = null
    // 重置日期确认状态
    resetDateConfirmation()
  }
})

watch(clearTag, (newTag) => {
  console.log('newTag', newTag)
  if (newTag > 0) {
    tagId.value = null
    store.setTag(null, null)
    activeTagIndex.value = -1
    nextTick(() => {
      emit('resetTagComplete')
    })
  }
})

watch(clearCity, (newCity) => {
  if (newCity) {
    showCityList.value = null
    // 重置城市确认状态
    resetCityConfirmation()
  }
})

//关于演出城市相关的筛选条件
const allCityFilter = ref([])
const hotAllCityFilter = ref([])
const hotTopCityFilter = ref([])
const locationCityFilter = ref(null)

//筛选的演出城市id 数组
const showCityList = ref(null)

// 当前查询页码
const pageNum = ref(1)

//查询分页大小参数
const length = ref(10)
//查询偏移量参数
// const offset = computed(() => {
//   console.log('计算 offset，pageNum:', pageNum.value, 'length:', length.value)
//   return (pageNum.value - 1) * length.value
// })
// 查询tag 参数
const tagId = ref('')
const activeTagIndex = ref(-1)

// 是否还有更多数据
const hasMore = ref(true)

//热门tags列表
const hotTags = ref([])

// 只选取前面8个热门tags
const previewHotTags = computed(() => hotTags.value?.slice(0, 8))

//全部tags列表
const allTags = ref([])

// 演出列表
const showList = ref([])

/* 生命周期 */
onMounted(async () => {
  // 获取分类列表
  await find_show_type(store.currentCity.cityId)
  //获取筛选条件  演出城市
  await find_city_list(store.currentCity.cityId)
  // 初始化筛选tag列表
  if (showType.value) {
    await find_tag_list(
      store.currentCity.cityId,
      showType.value,
      showCityList.value,
      dateFilter.beginDateTime,
      dateFilter.endDateTime,
    )
  }
})

// 监听 pageNum 变化
watch(pageNum, (newVal, oldVal) => {
  // console.log(`pageNum 从 ${oldVal} 变为 ${newVal}`)
  // console.trace('pageNum 变化调用栈')
})

// 监听 find_show_type 和 find_city_list 方法的参数变化
watch(
  () => store.currentCity.cityId,
  async (newCityId) => {
    await find_show_type(newCityId)
    await find_city_list(newCityId)
  },
)

// 监听 popup 修改的typeName
watch(
  () => showTypeName.value,
  async (newTypeName) => {
    // 重置页码
    pageNum.value = 1
    // 清空当前列表
    showList.value = []

    console.log('监听 popup 修改的typeName')
    await find_show_list(
      store.currentCity.cityId,
      newTypeName,
      showCityList.value,
      dateFilter.beginDateTime,
      dateFilter.endDateTime,
      sorting.value,
      length.value,
      (pageNum.value - 1) * length.value,
      // tagId.value,
      store.tag.tagId,
    )
  },
)

// 监听  find_tag_list 方法的参数变化
watch(
  [
    () => store.currentCity.cityId,
    () => showType.value,
    () => showCityList.value,
    () => dateFilter.beginDateTime,
    () => dateFilter.endDateTime,
  ],
  async ([newCityId, newShowType, newShowCityList, newBeginDateTime, newEndDateTime]) => {
    await find_tag_list(newCityId, newShowType, newShowCityList, newBeginDateTime, newEndDateTime)
  },
)

// 监听 find_show_list 方法的参数变化
watch(
  [
    () => store.currentCity.cityId,
    () => showType.value,
    () => showCityList.value,
    () => dateFilter.beginDateTime,
    () => dateFilter.endDateTime,
    () => sorting.value,
    () => length.value,
    //  () => offset.value,
    //() => tagId.value,
    () => store.tag.tagId,
  ],
  async ([
    newCityId,
    newShowType,
    newShowCityList,
    newBeginDateTime,
    newEndDateTime,
    newSorting,
    newLength,
    newTagId,
  ]) => {
    if (
      newCityId === undefined ||
      newCityId === null ||
      newShowType === null ||
      newShowType === undefined
    ) {
      console.warn('必要参数未准备好，跳过查询')
      return
    }

    // 重置页码为1，因为筛选条件变化时应该重新从第一页开始
    pageNum.value = 1

    console.log('监听 find_show_list 方法的参数变化')

    // 当筛选条件变化时，清空列表
    showList.value = []
    await find_show_list(
      newCityId,
      newShowType,
      newShowCityList,
      newBeginDateTime,
      newEndDateTime,
      newSorting,
      newLength,
      (pageNum.value - 1) * newLength, // 手动计算 offset
      newTagId,
    )
  },
  { deep: true }, // 添加深度监听
)

/* 方法实现 */
// tab 点击
const clickTab = ({ name }) => {
  // console.log('name:', name) //索引值
  // console.log('active:', active.value) //索引值
  // showToast(name)
  //当前选中的tab
  // showType.value = categories.value[name].showTypeName
}
// tag 点击
const clickTag = (tag, index) => {
  if (tag) {
    tagId.value = tag.tagId
    store.setTag(tag.tagName, tag.tagId)
  }
  if (index) {
    activeTagIndex.value = index
  } else {
    activeTagIndex.value = -1
    // 弹窗显示更多tag
    emit('showMoreTags')
  }
}

// 获取分类列表
const find_show_type = async (cityId) => {
  try {
    const { statusCode, data } = await fetchCategoryList(cityId)
    if (statusCode === 200) {
      categories.value = data
      // console.log(" 分类页 顶部  categories", categories.value)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 演出城市选择项
const find_city_list = async (cityId) => {
  try {
    const {
      statusCode,
      data: { allCity, hotAllCity, hotTopCity, locationCity },
    } = await fetchShowCity(cityId)
    if (statusCode === 200) {
      allCityFilter.value = allCity
      hotAllCityFilter.value = hotAllCity
      hotTopCityFilter.value = hotTopCity
      locationCityFilter.value = locationCity
    }
  } catch (error) {
    console.error('获取演出城市选择项出错', error)
  }
}

// 演出筛选tag
const find_tag_list = async (cityId, showType, showCityList, beginDateTime, endDateTime) => {
  try {
    const {
      statusCode,
      data: { hotTagList, allTagList },
    } = await fetchShowFilterTag(cityId, showType, showCityList, beginDateTime, endDateTime)
    // console.log('find_tag_list', res)
    if (statusCode === 200) {
      hotTags.value = hotTagList
      allTags.value = allTagList
      store.setAllTags(allTagList)
    }
  } catch (error) {
    console.error('获取演出筛选tag出错', error)
  }
}

// 演出列表查询
const find_show_list = async (
  cityId,
  showType,
  showCityList,
  beginDateTime,
  endDateTime,
  sorting,
  reqLength,
  offset,
  tagId,
) => {
  try {
    // console.log('开始请求数据...')
    console.log(
      `find_show_list请求参数: cityId =${cityId},showType=${showType},showCityList=${showCityList},beginDateTime=${beginDateTime},endDateTime=${endDateTime},sorting=${sorting},length=${reqLength},offset=${offset},tagId=${tagId}`,
    )

    const {
      statusCode,
      data: { searchData },
    } = await fetchShowList(
      cityId,
      showType,
      showCityList,
      beginDateTime,
      endDateTime,
      sorting,
      reqLength,
      offset,
      tagId,
    )

    if (statusCode === 200) {
      if (searchData.length > 0) {
        if (pageNum.value === 1) {
          showList.value = []
          showList.value = [...searchData] // 首页替换数据
        } else {
          showList.value.push(...searchData) // 加载更多时追加数据
        }
        // 修复分页逻辑判断: 当返回的数据量等于请求的数据量时，才可能有更多数据
        // 如果返回的数据量小于请求的数据量，说明已经到最后一页
        if (searchData.length < length.value) {
          // console.log('1 searchData.length :', searchData.length)
          // console.log('1 length.value :', length.value)

          hasMore.value = false
        } else {
          hasMore.value = true
          // console.log('2 searchData.length :', searchData.length)
          // console.log('2 length.value :', length.value)
        }
        // console.log('请求成功，hasMore 状态:', hasMore.value)
      } else {
        // 没有数据返回时清空列表（仅在第一页时）
        if (pageNum.value === 1) {
          showList.value = []
        }
        hasMore.value = false
      }
    } else {
      console.log('请求失败，状态码:', statusCode)
      // 请求失败时，如果是第一页则清空列表
      if (pageNum.value === 1) {
        showList.value = []
      }
      hasMore.value = false // 请求失败时也停止加载更多
    }
    // 确保无论如何都关闭 整个页面loading 状态
    emit('update:loading', false)
  } catch (error) {
    console.error('演出列表查询出错:', error)
    // 出错时，如果是第一页则清空列表
    if (pageNum.value === 1) {
      showList.value = []
    }
    hasMore.value = false // 出错时停止加载更多
    emit('update:loading', false)
  } finally {
    // 这里需要让category组件的loading状态为false
    emit('close:loading', false)
  }
}

//加载下一页演出列表数据
const handleLoadMore = async () => {
  // console.log('handleLoadMore 被调用，当前页码:', pageNum.value)
  // console.log('当前 hasMore 状态:', hasMore.value)

  if (!hasMore.value || hasMore.value === null || hasMore.value === undefined) {
    // console.log('没有更多数据，跳过 handleLoadMore')
    return
  }

  try {
    console.log('执行 handleLoadMore')
    // 直接调用 find_show_list，而不是依赖 watch
    await find_show_list(
      store.currentCity.cityId,
      showType.value,
      showCityList.value,
      dateFilter.beginDateTime,
      dateFilter.endDateTime,
      sorting.value,
      length.value,
      (pageNum.value - 1) * length.value, // 手动计算 offset，避免响应式依赖循环
      //tagId.value,
      store.tag.tagId,
    )

    pageNum.value++
    // console.log('页码增加后:', pageNum.value)
  } catch (error) {
    console.error('加载更多数据出错:', error)
    // 出错时回退页码
    pageNum.value--
    throw error // 重新抛出错误，让调用者处理
  }
}
// 打开分类popup菜单
const showCategoryPopup = () => {
  emit('openCategoryPopup', { bool: true, category: categories.value })
}

//点击选择排序方式
const changeSorting = (value) => {
  showToast(value)
}

// 判断日期是否为今天
const formatter = (day) => {
  const today = new Date()
  // 判断是否为今天
  if (
    day.date.getFullYear() === today.getFullYear() &&
    day.date.getMonth() === today.getMonth() &&
    day.date.getDate() === today.getDate()
  ) {
    // 如果是今天，修改 text 属性
    day.text = '今天'
  }

  day.bottomInfo = ''
  day.topInfo = ''

  // 返回修改后的 day 对象
  return day
}

// 点击日期单元格
const onSelect = (value) => {
  if (value.length === 1) {
    showToast({
      message: '请再选择结束日期',
      duration: 1500,
    })
  }
}

//重置日期
const reset = () => {
  if (calendarRef.value) calendarRef.value.reset()
}

// 确定选择的日期
const confirm = () => {
  if (calendarRef.value) {
    const [start, end] = calendarRef.value.getSelectedDate() // 获取选中的日期

    // 格式化成 YYYYMMDD 字符串
    dateFilter.beginDateTime = formatDateToYYYYMMDD(start)
    dateFilter.endDateTime = formatDateToYYYYMMDD(end)

    // 保存选择的日期
    store.setBeginDateTime(formatDateToMMDD(start))
    store.setEndDateTime(formatDateToMMDD(end))

    // 设置日期已确认标志
    isDateConfirmed.value = true

    //关闭日历控件
    if (dateDropDownRef.value) dateDropDownRef.value.toggle(false)
  }
}

// 选择城市
const updateCityId = async (cityId) => {
  // 选择的城市
  showCityList.value = cityId
}

// 关闭城市选择
const closeCityOption = (bool) => {
  if (cityDropDownRef.value) {
    cityDropDownRef.value.toggle(bool)
  }
}

defineExpose({
  hasMore,
  handleLoadMore,
  showList,
  clickTag,
})
</script>

<style scoped lang="scss">
.filter-tags {
  background-color: #fff;
  display: flex;
  align-items: center;
  overflow-x: auto;
  gap: 8px;
  padding: 0 15px;
  margin-top: 10px;

  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */

  &::-webkit-scrollbar {
    display: none;
    /* Chrome Safari */
  }

  .tag {
    flex: 0 0 auto;
    background: #f5f5f5;
    color: #323038;
    font-size: 12px;
    font-weight: 500;
    padding: 6px 12px;

    &.active {
      color: #ff1d41;
    }
  }
}

i.van-badge__wrapper.van-icon.van-icon-wap-nav.more {
  position: fixed;
  right: 0px;
  z-index: 5;
  background: #fff;
  width: 30px;
  font-size: 30px;
}

:deep(.van-tabs__nav) {
  align-items: center;
}

:deep(.tab-title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.van-tab--active) {
  color: #000000;
  font-size: 20px;
  font-weight: 700;
}

:deep(.van-dropdown-menu__bar) {
  box-shadow: none;
}

:deep(.van-calendar__day--start-end) {
  background: rgba(255, 72, 134, 0.15);
}

:deep(.van-calendar__day--start) {
  background: rgba(255, 72, 134, 0.15);
}

:deep(.van-calendar__day--end) {
  background: rgba(255, 72, 134, 0.15);
}

.van-calendar__day--middle {
  background-color: #fff6fa;
}

:deep(.van-calendar__day.van-calendar__day--middle) {
  background-color: #fff6fa;
}

:deep(.van-calendar__footer) {
  border: 1px solid #ccc;
}

.rules {
  background-color: #fff;

  .sort {}

  .show-date {
    .calendar {
      .custom-calendar {
        height: calc(100vh - 256px);
        position: relative;
      }

      .month-title {
        text-align: left;
        padding-left: 10px;
        font-size: 16px;
        font-weight: 500;
      }

      .buttons {
        width: 100%;
        display: flex;
        align-items: center;
        padding: 10px 0;
        justify-content: space-between;
        gap: 10px;
      }
    }
  }

  .how-city {}
}

span.van-dropdown-menu__title.sort-class .van-ellipsis {
  color: red;
}
</style>
